﻿using Hwh_VoteSys.Models.Database;
using Hwh_VoteSys.Models.Vote_List;
using Hwh_VoteSys.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Transactions;

namespace Hwh_VoteSys.Controllers
{
	/// <summary>
	/// 投票列表
	/// </summary>
	[Route("api/[controller]/[action]")]
	[ApiController]
	public class Voting_List : Controller
	{
		//定义数据库上下文
		private readonly Hwh_VoteSysContext _db;
		private readonly IJWTService _jwtService;
		public Voting_List(Hwh_VoteSysContext db, IJWTService jwtService)
		{
			_db = db;
			_jwtService = jwtService;
		}

		/// <summary>
		/// 获取投票项目列表接口
		/// </summary>
		/// <param name="Com_ProjectType"></param>
		/// <param name="ComName"></param>
		/// <param name="Page"></param>
		/// <returns></returns>
		/// 按照[投票列表]设计稿内容展示投票项目的部分内容，并且显示实时票数
		/// 需要按照3个项目类别区分项目展示
		/// 需要有搜索、分页功能对投票项目进行展示
		/// 输入：类别、搜索关键字、分页信息
		/// 输出：所需展示内容信息
		[HttpGet]
		public List<CompanyDataUpload> company_Votes(string Com_ProjectType, string ComName, int Page)
		{
			//定义返回列表
			List<Company_Vote_List> List = new List<Company_Vote_List>();
			//查询CompanyDataUpload
			var CompanyDataUpload = _db.CompanyDataUploads.AsQueryable();
			//定义每页显示数量
			int PageSize = 4;
			//定义起始位置
			int Start = (Page - 1) * PageSize;
			//定义结束位置
			int End = Page * PageSize;
			//定义总数
			int Total = 0;
			//定义查询列表
			List<CompanyDataUpload> CompanyDataUploads = new List<CompanyDataUpload>();
			//判断项目是否审核通过
			if(CompanyDataUpload == null)
			{
				return null;
			}
			CompanyDataUpload = CompanyDataUpload.Where(x => x.ReviewStatus == 1);
			//判断是否有搜索关键字
			if (ComName == null)
			{
				//判断是否有项目类别
				if (Com_ProjectType == null)
				{
					//查询所有
					CompanyDataUploads = _db.CompanyDataUploads.ToList();
				}
				else
				{
					//查询项目类别
					CompanyDataUploads = _db.CompanyDataUploads.Where(x => x.ComProjectType == Com_ProjectType).ToList();
				}
			}
			else
			{
				//判断是否有项目类别
				if (Com_ProjectType == null)
				{
					//查询搜索关键字
					CompanyDataUploads = _db.CompanyDataUploads.Where(x => x.ComName.Contains(ComName)).ToList();
				}
				else
				{
					//查询项目类别和搜索关键字
					CompanyDataUploads = _db.CompanyDataUploads.Where(x => x.ComProjectType == Com_ProjectType && x.ComName.Contains(ComName)).ToList();
				}
			}
			//获取总数
			Total = CompanyDataUploads.Count;
			//判断是否有数据
			if (CompanyDataUploads.Count > 0)
			{
				//循环获取数据
				for (int i = Start; i < End; i++)
				{
					//判断是否超出总数
					if (i < Total)
					{
						//添加数据 显示实时票数
						List.Add(new Company_Vote_List
						{
							ComLogo = CompanyDataUploads[i].ComLogo,
							ComName = CompanyDataUploads[i].ComName,
							Com_ProjectType = CompanyDataUploads[i].ComProjectType,
							VNum = CompanyDataUploads[i].VNum.Value
						});
						CompanyDataUploads[i].VNum = _db.Votes.Count(x => x.ComId == CompanyDataUploads[i].ComId);
					}
				}
			}
			//返回数据
			return CompanyDataUploads;
		}

		/// <summary>
		/// 投票接口（需授权）
		/// </summary>
		/// <param name="Com_Id"></param>
		/// <returns></returns>
		[HttpPost]
		[Authorize]
		public string Vote(int Com_Id)
		{
			//开启事务锁 保证数据的一致性 死锁
			using var scope = new TransactionScope();
			try
			{
				//获取当前用户
				var uid = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
				//获取公司的投票数
				var companyVote = _db.CompanyDataUploads.FirstOrDefault(x => x.ComId == Com_Id);
				//判断用户是否登录
				if (uid == null)
				{
					return "请先登录";
				}
				//获取当前时间
				var now = DateTime.Now;
				//获取当天时间
				var today = now.Date;
				//获取用户当天投票次数
				var count = _db.Votes.Count(x => x.UId == int.Parse(uid) && x.CreateTime >= today);
				//判断该项目是否存在
				if (companyVote == null)
				{
					return "该项目不存在";
				}
				//判断该项目是否审核通过
				if (companyVote.ReviewStatus != 1)
				{
					return "该项目未审核通过，不能投票";
				}
				//判断用户当天投票次数
				if (count > 5)
				{
					return "今天投票次数已用完";
				}
				//添加投票记录，并且通过连接公司表，每一次添加投票记录，公司的投票数加1
				_db.Votes.Add(new Vote
				{
					UId = int.Parse(uid),
					ComId = Com_Id,
					CreateTime = now
				});
				//投票数加1
				companyVote.VNum++;
				//保存数据
				var row = _db.SaveChanges();
				if (row > 0)
				{
					scope.Complete();
					//返回投票成功
					return "投票成功";
				}
				return "投票失败";
			}
			catch (Exception ex)
			{
				return ex.Message;
			}
		}
	}
}
